package com.ifast.check.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.ifast.asset.domain.AssetAndGroup;
import com.ifast.asset.domain.AssetAndGroupDO;
import com.ifast.asset.domain.Assets;
import com.ifast.asset.service.AssetAndGroupService;
import com.ifast.asset.service.AssetsService;
import com.ifast.asset.util.HttpUtil;
import com.ifast.check.entity.CheckEntity;
import com.ifast.check.entity.MqTaskRequest;
import com.ifast.check.service.RabbitMQServiceImpl;
import com.ifast.check.utils.ScoreUtil;
import com.ifast.common.utils.Result;
import io.swagger.annotations.Api;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wxmp/check")
@Api(value = "核查接口")
//核查任务借口
public class CheckTask {

    @Value("${auditUrl}")
    String auditUrl;
    @Value("${user}")
    String username;
    @Value("${password}")
    String password;
    @Autowired
    private AssetsService assetsService;
    @Autowired
    private RabbitMQServiceImpl rabbitMQServiceImpl;
    @Autowired
    private AssetAndGroupService assetAndGroupService;

    public static String token = "";
    public static String portid = "730ef368-57e2-11e1-a90f-406186ea4fc5";

    //获取Token接口(登录)
    @ResponseBody
    @GetMapping("/getToken")
    public Result<Object> getToken() {

        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        String url = auditUrl + "/user/login";
        String res = HttpUtil.sendPost(url, JSON.toJSONString(map));
        //解析token
        JSONObject json = JSONObject.parseObject(res);
        token = json.getString("data");
        return Result.ok();
    }

    //获取核查任务列表
    @ResponseBody
    @GetMapping("/getTasksList")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getTasksList(Integer pageNum, Integer pageSize) {

        Map<String, Object> map = new HashMap<>();
        map.put("currentPage", pageNum);
        map.put("pageSize", pageSize);
        String url = auditUrl + "/getTasksList";
        String res = HttpUtil.sendPost(url, JSON.toJSONString(map), token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //获取未完成核查任务个数
    @ResponseBody
    @GetMapping("/getTasksNum")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getTasksNum() {

        String url = auditUrl + "/getTasksNum";
        String res = HttpUtil.sendPost(url, "", token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //获取核查对象借口
    @ResponseBody
    @GetMapping("/getTargetList")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getTargetList(Integer pageNum, Integer pageSize) {

        Map<String, Object> map = new HashMap<>();
        map.put("currentPage", pageNum);
        map.put("pageSize", pageSize);
        String url = auditUrl + "/getTargetList";
        String res = HttpUtil.sendPost(url, JSON.toJSONString(map), token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //核查端口集和默认
    @ResponseBody
    @GetMapping("/getPortList")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getPortList(Integer pageNum, Integer pageSize) {

        Map<String, Object> map = new HashMap<>();
        map.put("currentPage", pageNum);
        map.put("pageSize", pageSize);
        String url = auditUrl + "/getPortList";
        String res = HttpUtil.sendPost(url, JSON.toJSONString(map), token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //添加核查对象
    @ResponseBody
    @GetMapping("/createTarget")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> createTarget(String hosts, String name) {

        Map<String, Object> map = new HashMap<>();
        map.put("hosts", hosts);
        map.put("name", name);
        map.put("portId", portid);
        String url = auditUrl + "/createTarget";
        String res = HttpUtil.sendPost(url, JSON.toJSONString(map), token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //添加任务
    @ResponseBody
    @GetMapping("/createTask")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> createTask(String type, String cron, String name, String targetId) {

        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("cron", cron);
        map.put("name", name);
        map.put("targetId", targetId);
        String url = auditUrl + "/createTask";
        String res = HttpUtil.sendPost(url, JSON.toJSONString(map), token);
        return Result.ok(JSONObject.parseObject(res));
    }


    //删除核查对象
    @ResponseBody
    @GetMapping("/deleteTarget")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> deleteTarget(String[] targetId) throws Exception {

        String url = auditUrl + "/deleteTarget";
        String res = HttpUtil.jsonDeleteRequest(url, JSON.toJSONString(targetId), token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //查询报告id
    @ResponseBody
    @GetMapping("/getReportIdByTaskID")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getReportIdByTaskID(String taskId) {

        String url = auditUrl + "/getReportIdByTaskID/" + taskId;
        String res = HttpUtil.sendGet(url, "", token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //根据 报告id  查询  检测结果
    @ResponseBody
    @GetMapping("/getReport")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getReport(String reportId) {

        String url = auditUrl + "/getReport/" + reportId;
        String res = HttpUtil.sendGet(url, "", token);
        return Result.ok(JSONObject.parseObject(res));
    }

    //根据ip查询出漏扫信息
    @ResponseBody
    @GetMapping("/getReportByHost")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getReportByHost(String ip) throws JSONException {

        int hig = 0, mid = 0, low = 0, warning = 0;
        String url = auditUrl + "/getReportByHost/" + ip;
        String res = HttpUtil.sendGet(url, "", token);
        //解析  报告信息  计算分数
        //System.out.println(res);
        JSONObject resJson = (JSONObject) JSONObject.parse(res);
        String data = resJson.getString("data");
        JSONArray dataArray = new JSONArray(data);
        for (int i = 0; i < dataArray.length(); i++) {

            JSONObject ary = (JSONObject) JSONObject.parse(dataArray.get(i).toString());
            String threat = ary.get("threat").toString();
            if ("高".equals(threat)) {
                hig++;
            } else if ("中".equals(threat)) {
                mid++;
            } else if ("低".equals(threat)) {
                low++;
            } else {
                warning++;
            }
        }
        String score = ScoreUtil.calculationScore(hig, mid, low, warning);

        //跟新安全分数
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("ip", ip);
        Assets assets = assetsService.selectOne(wrapper);
        if (assets != null && assets.getScore() == 0) {
            assets.setScore(Double.valueOf(score));
            assetsService.updateById(assets);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("score", score);
        map.put("res", res);
        map.put("hig", hig);
        map.put("mid", mid);
        map.put("low", low);
        map.put("warning", warning);
        return Result.ok(map);
    }

    //新的添加扫描对象并且添加任务接口
    @ResponseBody
    @PostMapping("/addTargetAndTasks")
    public Result<Object> addTargetAndTasks(@RequestBody CheckEntity checkEntity) {
        String resTask = "";
        for (int i = 0; i < checkEntity.getHosts().length; i++) {
            String targetid = "";
            //先验证是否存在此IP的查询目标
            try {
                //获取targetId扫描任务的targetid
                String getTagetUrl = auditUrl + "/getTargetIdByIp/" + checkEntity.getHosts()[i];
                String getTargetRes = HttpUtil.sendGet(getTagetUrl, "", token);
                JSONObject resJson = (JSONObject) JSONObject.parse(getTargetRes);
                targetid = resJson.get("data").toString();
            } catch (Exception e) {
                //return Result.ok("creat error");
            }
            if ("".equals(targetid)) {
                //先添加扫描对象  在添加 扫描任务
                Map<String, Object> map = new HashMap<>();
                map.put("hosts", checkEntity.getHosts()[i]);
                map.put("name", checkEntity.getHosts()[i]);
                map.put("portId", portid);
                String url = auditUrl + "/createTarget";
                String res = HttpUtil.sendPost(url, JSON.toJSONString(map), token);
                if ("".equals(res)) {
                    return Result.ok("creat error");
                }
            }
            try {
                //获取targetId扫描任务的targetid
                String getTagetUrl = auditUrl + "/getTargetIdByIp/" + checkEntity.getHosts()[i];
                String getTargetRes = HttpUtil.sendGet(getTagetUrl, "", token);
                JSONObject resJson = (JSONObject) JSONObject.parse(getTargetRes);
                targetid = resJson.get("data").toString();
            } catch (Exception e) {
                return Result.ok("creat error");
            }
            //继续执行添加扫描任务
            Map<String, Object> mapTask = new HashMap<>();
            mapTask.put("type", checkEntity.getType());
            mapTask.put("cron", checkEntity.getCron());
            mapTask.put("name", checkEntity.getName() + checkEntity.getHosts());
            mapTask.put("targetId", targetid);
            String urlTask = auditUrl + "/createTask";
            resTask = HttpUtil.sendPost(urlTask, JSON.toJSONString(mapTask), token);

        }
        return Result.ok(resTask);
    }


    //获取有报告的ip列表
    @ResponseBody
    @GetMapping("/getHasReportIp")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getHasReportIp(String pageSize, String currentPage) {

        String url = auditUrl + "/getHasReportIp/" + currentPage + "/" + pageSize;
        String res = HttpUtil.sendGet(url, "", token);
        return Result.ok(JSONObject.parseObject(res));
    }



    //风险对比函数
    @ResponseBody
    @GetMapping("/comparedReports")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> comparedReports(String reportId1, String reportId2) {

        //根据两次报告id  获取报告结果
        String url1 = auditUrl + "/getReport/" + reportId1;
        String res1String = HttpUtil.sendGet(url1, "", token);
        JSONObject res1 = JSONObject.parseObject(res1String);

        String url2 = auditUrl + "/getReport/" + reportId2;
        String res2String = HttpUtil.sendGet(url2, "", token);
        JSONObject res2 = JSONObject.parseObject(res2String);

        List<Object> res1List = new ArrayList<>();
        List<Object> res2List = new ArrayList<>();
        //对比两次安全扫描,并将结果返回
        try {
            JSONArray dataArrayres1 = new JSONArray(res1.getString("data"));
            JSONArray dataArrayres2 = new JSONArray(res2.getString("data"));
            for (int i = 0; i < dataArrayres1.length(); i++) {

                JSONObject ob1 = JSONObject.parseObject(dataArrayres1.get(i).toString());
                if (!res2String.contains(ob1.getString("cveName"))) {

                    res1List.add(ob1);
                }
            }
            for (int i = 0; i < dataArrayres2.length(); i++) {

                JSONObject ob2 = JSONObject.parseObject(dataArrayres2.get(i).toString());
                if (!res1String.contains(ob2.getString("cveName"))) {

                    res2List.add(ob2);
                }
            }

        } catch (Exception e) {

        }
        Map<String, Object> map = new HashMap<>();
        map.put("report1", res1List);
        map.put("report2", res2List);
        return Result.ok(map);
    }

    //风险对比函数2
    @ResponseBody
    @GetMapping("/comparedReportsNew")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> comparedReportsNew(String reportId1, String reportId2) {

        //根据两次报告id  获取报告结果
        String url1 = auditUrl + "/getReport/" + reportId1;
        String res1String = HttpUtil.sendGet(url1, "", token);
        JSONObject res1 = JSONObject.parseObject(res1String);

        String url2 = auditUrl + "/getReport/" + reportId2;
        String res2String = HttpUtil.sendGet(url2, "", token);
        JSONObject res2 = JSONObject.parseObject(res2String);
        Map<String, Object> map = new HashMap<>();
        List<String> resAllList = new ArrayList<>();
        //对比两次安全扫描,并将结果返回
        try {
            JSONArray dataArrayres1 = new JSONArray(res1.getString("data"));
            JSONArray dataArrayres2 = new JSONArray(res2.getString("data"));
            for (int i = 0; i < dataArrayres1.length(); i++) {

                if (!resAllList.contains(dataArrayres1.get(i))) {

                    resAllList.add(dataArrayres1.get(i).toString());
                }
            }
            for (int i = 0; i < dataArrayres2.length(); i++) {

                if (!resAllList.contains(dataArrayres2.get(i))) {

                    resAllList.add(dataArrayres2.get(i).toString());
                }
            }
            map.put("report1", res1.getString("data"));
            map.put("report2", res2.getString("data"));
            map.put("resAllList", resAllList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok(map);
    }

    //按照ip删除所有信息
    @ResponseBody
    @GetMapping("/deleteAllByIp")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> deleteAllByIp(String[] ip) throws Exception {

        String url = auditUrl + "/deleteAllByIp";
        String res = HttpUtil.jsonDeleteRequest(url, JSON.toJSONString(ip), token);
        return Result.ok(JSONObject.parseObject(res));
    }



    //分组添加   查询    删除   详情接口****************************************************************************
    //单个任务添加查看列表
    @ResponseBody
    @GetMapping("/getIpTask/{currentPage}/{pageSize}")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getIpTask(@PathVariable Integer currentPage, @PathVariable Integer pageSize) {

        String url = auditUrl + "/getIpTask/" + currentPage + "/" + pageSize;
        String res = HttpUtil.sendGet(url, "", token);
        return Result.ok(JSONObject.parseObject(res));
    }
    //单个任务添加
    @ResponseBody
    @GetMapping("/addTargetAndTasks")
    public Result<Object> addTargetAndTasks(String ip, String name, String type, String cron,String checkType) {

        String hosts = ip;
        String targetid = "";
        //先验证是否存在此IP的查询目标
        try {
            //获取targetId扫描任务的targetid
            String getTagetUrl = auditUrl + "/getTargetIdByIp/" + hosts;
            String getTargetRes = HttpUtil.sendGet(getTagetUrl, "", token);
            JSONObject resJson = (JSONObject) JSONObject.parse(getTargetRes);
            targetid = resJson.get("data").toString();
        } catch (Exception e) {
            //return Result.ok("creat error");
        }
        if ("".equals(targetid)) {
            //先添加扫描对象  在添加 扫描任务
            Map<String, Object> map = new HashMap<>();
            map.put("hosts", hosts);
            map.put("name", hosts);
            map.put("portId", portid);
            String url = auditUrl + "/createTarget";
            String res = HttpUtil.sendPost(url, JSON.toJSONString(map), token);
            if ("".equals(res)) {
                return Result.ok("creat error");
            }
        }
        try {
            //获取targetId扫描任务的targetid
            String getTagetUrl = auditUrl + "/getTargetIdByIp/" + hosts;
            String getTargetRes = HttpUtil.sendGet(getTagetUrl, "", token);
            JSONObject resJson = (JSONObject) JSONObject.parse(getTargetRes);
            targetid = resJson.get("data").toString();
        } catch (Exception e) {
            return Result.ok("creat error");
        }
        //继续执行添加扫描任务
        Map<String, Object> mapTask = new HashMap<>();
        mapTask.put("type", type);
        mapTask.put("cron", cron);
        mapTask.put("name", name);
        mapTask.put("targetId", targetid);
        mapTask.put("checkType",checkType);
        String urlTask = auditUrl + "/createTask";
        String resTask = HttpUtil.sendPost(urlTask, JSON.toJSONString(mapTask), token);

        return Result.ok(JSONObject.parseObject(resTask));
    }

    //删除单个任务
    @ResponseBody
    @GetMapping("/deleteTask")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> deleteTask(String[] taskId) throws Exception {

        String url = auditUrl + "/deleteTask";
        String res = HttpUtil.jsonDeleteRequest(url, JSON.toJSONString(taskId), token);
        return Result.ok(JSONObject.parseObject(res));
    }
    //通过Ip获取报告Id
    @ResponseBody
    @GetMapping("/getReportIdByIp")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getReportIdByIp(String ip) {

        String url = auditUrl + "/getReportIdByIp/" + ip;
        String res = HttpUtil.sendGet(url, "", token);
        return Result.ok(JSONObject.parseObject(res));
    }
    //获取任务组
    @ResponseBody
    @GetMapping("/getGroupTask/{currentPage}/{pageSize}")
    //@RequiresPermissions("wxmp:assets:list")
    public Result<Object> getGroupTask(@PathVariable Integer currentPage, @PathVariable Integer pageSize) {

        String url = auditUrl + "/getGroupTask/" + currentPage + "/" + pageSize;
        String res = HttpUtil.sendGet(url, "", token);
        return Result.ok(JSONObject.parseObject(res));
    }
    //详情
    @ResponseBody
    @PostMapping("/getMqTaskAdded")
    public Result<Object> getMqTaskAdded(@RequestBody MqTaskRequest mqTaskRequest) {
        String urlTask = auditUrl + "/getMqTaskAdded";
        String resTask = HttpUtil.sendPost(urlTask, JSON.toJSONString(mqTaskRequest), token);
        return Result.ok(JSONObject.parseObject(resTask));
    }


    //删除添加mq任务记录
    @ResponseBody
    @PostMapping("/deleteGroupTask")
    public Result<Object> deleteMqTask(@RequestBody List<Integer> groupIdList) {
        String urlTask = auditUrl + "/deleteGroupTask";
        String resTask = HttpUtil.sendPost(urlTask, JSON.toJSONString(groupIdList), token);
        return Result.ok(JSONObject.parseObject(resTask));
    }
    //分组添加
    @ResponseBody
    @PostMapping("/addTargetAndTasksRabbitmq")
    public Result<Object> addTargetAndTasksRabbitmq(@RequestBody CheckEntity checkEntity) {


        String urlTask = auditUrl + "/addTargetAndTasksRabbitmq";
        String resTask = HttpUtil.sendPost(urlTask, JSON.toJSONString(checkEntity), token);
        return Result.ok(JSONObject.parseObject(resTask));
    }

}







